<?php
declare(strict_types=1);

namespace app\index\controller;

use Swoole\Http\Request;
use Swoole\Http\Response;
use sys\Log;
use sys\services\JsonWebSocket;
use \app\index\services\CenterWebSocket;

class Center
{
    // 这是一个 WebSocket入口.
    public function index(Request $request, Response $response)
    {
        $check = validate([
            'token'=>'requireIfNot:unik',
            'sid'=>'require|uinteger'
        ], __LINE__ . __FILE__)->check($request->get);
        if(!$check->pass()){
            return json(['success'=>false,'message'=>'请求非法!'], 402);
        }
        // 1. 登录认证

        // 2. 升级为websocket
        try{
            if(false === upgrade($request, $response, JsonWebSocket::class, CenterWebSocket::class)){
                return json(['success'=>false,'message'=>'handshake failed!'], 402);
            }
            return true;
        }catch(\Throwable $e){
            echo "error: ". $e->getMessage(). "\n";
        }
        return true;
    }
}